from django.shortcuts import render
import json
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.conf import settings
import os


# Create your views here.
from .serializers import *
from rest_framework import viewsets
from .models import *


from rest_framework.pagination import PageNumberPagination
from rest_framework.decorators import action

# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend, CharFilter

from django_filters import FilterSet, DateFilter

from django.utils.timezone import make_aware
from datetime import datetime, timedelta

from django.http import HttpResponse
from datetime import datetime

# views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.schemas import AutoSchema, coreapi
import coreschema

# from rest_framework.schemas.openapi import AutoSchema
from rest_framework import serializers
from coreapi import Field
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.db.models import F

# 当前时间
print(datetime.now())
print(type(datetime.now()))
now = make_aware(datetime.now())

# 时间范围：现在往前推7天，现在往后推3天
start_date = now - timedelta(days=7)
end_date = now + timedelta(days=3)

print(start_date)

print(end_date)


class MyPagination(PageNumberPagination):
    page_size = 10  # 设置默认分页长度为10
    page_size_query_param = "page_size"  # 允许通过查询参数改变分页长度
    max_page_size = 240  # 最大分页长度


# 能源数据过滤器
class Fine_as_Filter(FilterSet):
    datetime_field = DateFilter(label="日期时间", field_name="time", lookup_expr="gte")

    class Meta:
        model = FineAs
        fields = ["station", "count_good", "count_reject", "ftq"]


class Fine_as_ViewSet(viewsets.ModelViewSet):
    print("运行该视图啦~")
    queryset = FineAs.objects.using("as_manage_analysis").all()

    serializer_class = As_manage_Serializer
    # 这是视图级别配置分页
    pagination_class = MyPagination
    # 参数过滤配置
    filter_backends = [DjangoFilterBackend]
    filterset_class = Fine_as_Filter

    def create(self, request, *args, **kwargs):
        print("post")
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def get_queryset(self):
        # query_params = self.request.query_params
        # start_time_param = query_params.get("start_time", None)
        # end_time_param = query_params.get("end_time", None)
        # start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
        # end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
        # queryset = FineAs.objects.using("as_manage_analysis").filter(
        #     time__gte=start_time_param_trans, time__lte=end_time_param_trans
        # )
        queryset = FineAs.objects.using("as_manage_analysis").all()
        return queryset

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class my_Fine_as(APIView):
    # 设置默认的每页数据量
    page_size = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="eun",
                required=False,
                location="query",
                schema=coreschema.String(description="发动机号"),
            ),
            Field(
                name="station_type",
                required=False,
                location="query",
                schema=coreschema.String(description="工位类型(A:自动站;M;手动站)"),
            ),
            Field(
                name="page",
                required=False,
                location="query",
                schema=coreschema.String(description="第几页"),
            ),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = As_manage_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = FineAs.objects.using("as_manage_analysis").filter().order_by("station")
        # 获取请求的参数
        id = request.query_params.get("id")
        station_type = request.query_params.get("station_type")
        eun = request.query_params.get("eun")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = FineAs.objects.using("as_manage_analysis").filter(id=id)
        if station_type is not None:
            queryset = queryset.filter(station__contains=station_type)
        if eun is not None:
            queryset = queryset.filter(eun=eun)

        return queryset


class CustomAutoSchema(AutoSchema):
    def get_manual_fields(self, path, method):
        extra_fields = [
            Field(
                name="date",
                location="query",
                required=False,
                schema=coreapi.coreschema.String(title="Date", description="Date in YYYY-MM-DD format"),
            ),
            Field(
                name="datetime",
                location="query",
                required=False,
                schema=coreapi.coreschema.String(title="Datetime", description="Datetime in ISO 8601 format"),
            ),
        ]
        fields = super().get_manual_fields(path, method)
        fields.extend(extra_fields)
        return fields


class my_OutputLoopa(APIView):
    # 设置默认的每页数据量
    page_size = 10
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(name="id", required=False, location="query", schema=coreschema.Number(description="id")),
            Field(name="eun", required=False, location="query", schema=coreschema.String(description="发动机号")),
            Field(
                name="station",
                required=False,
                location="query",
                schema=coreschema.String(description="工位"),
            ),
            Field(
                name="station_type",
                required=False,
                location="query",
                schema=coreschema.String(description="工位类型(A:自动站;M;手动站)"),
            ),
            Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
            Field(
                name="start_time",
                required=False,
                location="query",
                schema=coreschema.String(description="开始日期时间"),
            ),
            Field(
                name="end_time",
                required=False,
                location="query",
                schema=coreschema.String(description="结束日期时间"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = OutputLoopa_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        # queryset = OutputLoopa.objects.using("as_manage_analysis").annotate(staion_order=F('staion')).order_by('staion_order')
        queryset = OutputLoopa.objects.using("as_manage_analysis").filter().order_by("station")
        # 获取请求的参数

        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        print(start_time_param)
        print(end_time_param)

        id = request.query_params.get("id")
        station = request.query_params.get("station")
        station_type = request.query_params.get("station_type")
        eun = request.query_params.get("eun")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = OutputLoopa.objects.using("as_manage_analysis").filter(id=id)
        if station is not None:
            queryset = queryset.filter(station__contains=station)
        if station_type is not None:
            queryset = queryset.filter(station__contains=station_type)
        if eun is not None:
            queryset = queryset.filter(eun=eun)
        if (start_time_param and end_time_param) is not None:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(time__gte=start_time_param_trans, time__lte=end_time_param_trans)
        else:
            print("aaaaa")

        return queryset


class my_AsCycle(APIView):
    # 设置默认的每页数据量
    page_size = 10
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="cycle",
                required=False,
                location="query",
                schema=coreschema.String(description="CT时间标准"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = AsCycle_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = AsCycle.objects.using("as_manage_analysis").all().order_by("-time")
        # 获取请求的参数
        id = request.query_params.get("id")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = AsCycle.objects.using("as_manage_analysis").filter(id=id)
        return queryset


class toolChangeDataView(APIView):
    # 设置默认的每页数据量
    page_size = 10
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(name="id", required=False, location="query", schema=coreschema.Number(description="id")),
            Field(
                name="op",
                required=False,
                location="query",
                schema=coreschema.String(description="op"),
            ),
            Field(
                name="tool_number",
                required=False,
                location="query",
                schema=coreschema.Number(description="tool_number"),
            ),
            Field(
                name="changetype",
                required=False,
                location="query",
                schema=coreschema.String(description="changetype"),
            ),
            Field(name="page", required=False, location="query", schema=coreschema.String(description="第几页")),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
            Field(
                name="start_time",
                required=False,
                location="query",
                schema=coreschema.String(description="开始日期时间，格式示例：2024-07-01 16:34:42"),
            ),
            Field(
                name="end_time",
                required=False,
                location="query",
                schema=coreschema.String(description="结束日期时间，格式示例：2024-07-10 16:34:42"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = toolChangeDataSerializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        # queryset = OutputLoopa.objects.using("as_manage_analysis").annotate(staion_order=F('staion')).order_by('staion_order')
        queryset = ToolChange.objects.using("tool_1").filter().order_by("createdate")
        # 获取请求的参数

        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)

        id = request.query_params.get("id")
        op = request.query_params.get("op")
        tool_number = request.query_params.get("tool_number")
        changetype = request.query_params.get("changetype")
        # shift = request.query_params.get("shift")
        # call_type = request.query_params.get("call_type")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if op is not None:
            queryset = queryset.filter(op__contains=op)
        if tool_number is not None:
            queryset = queryset.filter(tool_number__contains=tool_number)
        if changetype is not None:
            queryset = queryset.filter(changetype__contains=changetype)
        if (start_time_param and end_time_param) is not None:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(createdate__gte=start_time_param_trans, createdate__lte=end_time_param_trans)
        else:
            print("OK")

        return queryset


class OutputLoopa_Filter(FilterSet):
    class Meta:
        model = OutputLoopa
        fields = [
            "eun",
            "station",
            "pano",
            "last_cycle_time",
            "current_cycle_time",
            "goodpiececount",
            "rejectpiececount",
            "time",
        ]


class OutputLoopa_ViewSet(viewsets.ModelViewSet):
    print("运行该视图啦~")
    queryset = OutputLoopa.objects.using("as_manage_analysis").all()

    serializer_class = OutputLoopa_Serializer
    # 这是视图级别配置分页
    pagination_class = MyPagination
    # 参数过滤配置
    filter_backends = [DjangoFilterBackend]
    filterset_class = OutputLoopa_Filter

    def create(self, request, *args, **kwargs):
        print("post")
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    # def get_queryset(self):
    # query_params = self.request.query_params
    # start_time_param = query_params.get("start_time", None)
    # end_time_param = query_params.get("end_time", None)
    # start_time_param_trans = datetime.strptime("2024-06-12 16:37:06", "%Y-%m-%d %H:%M:%S")
    # end_time_param_trans = datetime.strptime("2024-06-12 16:37:26", "%Y-%m-%d %H:%M:%S")
    # queryset = OutputLoopa.objects.using("as_manage_analysis").filter(
    #     time__gte=start_time_param_trans, time__lte=end_time_param_trans
    # )
    # queryset = OutputLoopa.objects.using("as_manage_analysis").all()[:100]
    # return queryset

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


# class AsCycle_Filter(FilterSet):
#     class Meta:
#         model = AsCycle
#         fields = [
#             "cycle",
#             "time",
#         ]
#         filter_overrides = {
#              models.CharField: {
#                  'filter_class': django_filters.CharFilter,
#                  'extra': lambda f: {
#                      'lookup_expr': 'icontains',
#                  },
#              },
#              models.BooleanField: {
#                  'filter_class': django_filters.BooleanFilter,
#                  'extra': lambda f: {
#                      'widget': forms.CheckboxInput,
#                  },
#              },
#          }


class AsCycle_ViewSet(viewsets.ModelViewSet):
    print("运行该视图啦~")
    queryset = AsCycle.objects.using("as_manage_analysis").all().order_by("-time")

    serializer_class = AsCycle_Serializer
    # 这是视图级别配置分页
    pagination_class = MyPagination
    # 参数过滤配置
    filter_backends = [DjangoFilterBackend]
    # filterset_class = AsCycle_Filter

    def create(self, request, *args, **kwargs):
        print("post")
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def get_queryset(self):
        # query_params = self.request.query_params
        # start_time_param = query_params.get("start_time", None)
        # end_time_param = query_params.get("end_time", None)
        # start_time_param_trans = datetime.strptime("2024-06-12 16:37:06", "%Y-%m-%d %H:%M:%S")
        # end_time_param_trans = datetime.strptime("2024-06-12 16:37:26", "%Y-%m-%d %H:%M:%S")
        # queryset = OutputLoopa.objects.using("as_manage_analysis").filter(
        #     time__gte=start_time_param_trans, time__lte=end_time_param_trans
        # )
        queryset = AsCycle.objects.using("as_manage_analysis").all().order_by("-time")
        return queryset

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


from rest_framework.request import Request
from django.template.loader import render_to_string


# 基于类视图编程
class my_viwe_list(APIView):
    pagination_class = MyPagination
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                type="number",
            ),
            Field(
                name="eun",
                required=False,
                location="query",
                type="string",
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取参数
        id = request.query_params.get("id")
        eun = request.query_params.get("eun")

        print(id)

        # 使用序列化器验证参数
        serializer = OutputLoopa_Serializer(data={"id": id, "eun": eun})
        serializer.is_valid(raise_exception=True)

        # 处理业务逻辑
        # ...
        queryset = OutputLoopa.objects.using("as_manage_analysis").all()
        # queryset = OutputLoopa.objects.using("as_manage_analysis").all()
        s = OutputLoopa_Serializer(instance=queryset, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

        # return Response({"message": "处理成功"})

    # def get(self, request, *args, **kwargs):
    #     query_params = request.query_params

    #     # 获取路径参数（如果有的话）
    #     path_params = self.kwargs

    #     # 获取请求体数据（通常用于POST或PUT请求）
    #     data = request.data

    #     # 返回响应
    #     return Response(
    #         {"query_params": query_params, "path_params": path_params, "data": data},
    #         status=status.HTTP_200_OK,
    #     )
    # queryset = OutputLoopa.objects.using("as_manage_analysis").all()
    # s = OutputLoopa_Serializer(instance=queryset, many=True)
    # return Response(s.data, status=status.HTTP_200_OK)

    def post(self, request):
        s = OutputLoopa_Serializer(data=request.data)
        if s.is_valid():
            s.save()
            return Response(s.data, status=status.HTTP_200_OK)
        return Response(s.errors, status=status.HTTP_400_BAD_REQUEST)


# 基于函数视图编程，如果要在docs接口文档显示，需要加上@api_view装饰器
@api_view(["GET"])
def custom_function_view(request):
    data = {"message": "This is a custom function-based view."}
    return Response(data, status=status.HTTP_200_OK)
